import { ActionType, ModalForm, PageContainer, ProColumns, ProDescriptions, ProDescriptionsItemProps, ProFormDigit, ProFormText, ProTable } from '@ant-design/pro-components';
import { Button, Drawer, message, Tree } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import services from '@/services/demo';

const menuApi = services.MenuController
const teacherApi = services.TeacherController
const relationApi = services.RelationController


/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (tId: string, ids: number[]) => {
  const hide = message.loading('正在修改');
  try {
    await relationApi.update({tid: parseInt(tId), ids})
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};


export default () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.TeacherType>();

  const columns: ProColumns<API.TeacherType>[] = [
    {
      title: '序号',
      dataIndex: 'tId',
      valueType: 'indexBorder',
    },
    {
      title: '工号',
      dataIndex: 'tTeacherid',
      valueType: 'text',
    },
    {
      title: '姓名',
      hideInSearch: true,
      dataIndex: 'tName',
      valueType: 'text',
    },
    {
      title: '电话',
      dataIndex: 'tPhone',
      valueType: 'text',
    },
    {
      title: '学院',
      dataIndex: 'tCollege',
      valueType: 'text',
    },
    {
      title: '操作',
      fixed: 'right',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Button
          type="primary"
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          查看权限
        </Button>,
      ],
    },
  ];


  const [treeData, setTreeData] = useState<any[]>([])
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  
  useEffect(() => {
    menuApi.queryList({}).then(res => {
      //console.log(res.data)
      setTreeData(res.data.map((it: API.MenuType) => generateTree(it)))
    })
  }, [])
  useEffect(() => {
    console.log('currentRow?.tId',currentRow?.tId)
    if (currentRow != undefined) {
      menuApi.allMenuByTId({
        tId: currentRow.tId,
        flat: true
      }).then(res => {
        console.log('putId(res.data)', res.data)
        setCheckedKeys(res.data.map((it: API.MenuType) => it.id))
      })
    }
  }, [currentRow])
  
  function onCheck(checkedKeysValue: any, info: any) {
    setCheckedKeys(checkedKeysValue);
    console.log('onCheck', checkedKeysValue, info);
  };

  function onSelect(selectedKeysValue: React.Key[], info: any) {
    console.log('onSelect', selectedKeysValue,info);
  };

  return (
    <PageContainer>
      <ProTable<API.TeacherType, API.TeacherType>
        headerTitle="权限列表"
        actionRef={actionRef}
        rowKey="tId"
        search={{
          labelWidth: 120,
        }}
        request={teacherApi.queryList}
        columns={columns}
      />
    <ModalForm
      width={640}
      title="教师权限"
      visible={createModalVisible}
      onVisibleChange={handleModalVisible}
      onFinish={async () => {
        if (currentRow == undefined) {
          handleModalVisible(false);
          setCurrentRow(undefined);
          return
        }

        console.log('确定', currentRow.tId, checkedKeys)
        const success = await handleUpdate(currentRow.tId, checkedKeys as number[]);
        
        if (success) {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }
      }}
    >
      <Tree
        checkable
        defaultExpandedKeys={[]}
        defaultCheckedKeys={[]}
        checkedKeys={checkedKeys}
        onCheck={onCheck}
        onSelect={onSelect}
        treeData={treeData}
      />
    </ModalForm>

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.tId && (
          <ProDescriptions<API.TeacherType>
            column={2}
            title={currentRow?.tId}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.tId,
            }}
            columns={columns as ProDescriptionsItemProps<API.TeacherType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

function generateTree(node: API.MenuType):{
  title: string;
  key: React.Key;
  children?: any;
} {
  if (node.children && node.children.length) {
    return {
      title: node.name,
      key: node.id,
      children: node.children.map((child: any) => generateTree(child)),
    }
  } else {
    return {
      title: node.name,
      key: node.id,
    }
  }
}

